//axios基础的封装
import axios from "axios";

const httpInstance = axios.create({
  //1.项目基地址
  // baseURL: 'http://localhost:8080',
  baseURL: '/api',
  //2.超时时间
  timeout: 5000
})

import { useUserStore } from "@/stores/userStore";
import { useSellerStore } from "@/stores/sellerStore";
import { useAddressStore } from "@/stores/addressStore";
import { useCartStore } from "@/stores/cartStore";
import { useAdminStore } from "@/stores/adminStore";
import router from "@/router";
import { ElMessage } from "element-plus";


//拦截器
// 添加请求拦截器
httpInstance.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  //携带token
  const userStore = useUserStore()
  const sellerStore = useSellerStore()
  const adminStore = useAdminStore()
  const sellerPaths = [
    '/category/sellerGetCategory',
    '/goods/sellerGetGoods',
    '/goods/createGoods',
    '/goods/stateChange',
    '/goods/deleteGoods',
    '/goods/sellerDetailGoods',
    '/goods/updateGoods',
    '/order/sellerOrder',
    '/order/sendGoods',
    '/seller/updatePwd',
    '/seller/sellerInfo',
    '/seller/updateAvatar',
    '/seller/update'
  ];
  const adminPaths = [
    '/admin/',
    '/category/adminGetCategory',
    '/category/addCategory',
    '/category/deleteCategory',
    '/category/detailCategory',
    '/category/updateCategory',
    '/category/adminGetCategoryInGoods',
    '/goods/adminGetGoods',
    '/goods/recommendChange',
    '/goods/adminStateChange',
    '/goods/adminDetailGoods',
    '/goods/adminGetGoodsComment',
    '/goods/commentStatusChange',
    '/user/adminGetUserInfo',
    '/seller/adminGetSellerInfo',
    '/seller/updateSellerStatus',
    '/user/updateUserStatus',
  ];
  // 根据接口路径匹配身份
  if (adminPaths.some(path => config.url.startsWith(path))) {
    // Admin 逻辑
    const token = adminStore.adminInfo.data?.token;
    if (token) config.headers.Authorization = token;
  } else if (sellerPaths.some(path => config.url.startsWith(path))) {
    // Seller 逻辑
    const token = sellerStore.sellerInfo.data?.token;
    if (token) config.headers.Authorization = token;
  } else {
    // User 逻辑
    const token = userStore.userInfo.data?.token;
    if (token) config.headers.Authorization = token;
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
httpInstance.interceptors.response.use(function (response) {
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么
  return response;
}, function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  const userStore = useUserStore()
  const addressStore = useAddressStore()
  const cartStore = useCartStore()
  //401token 失效处理
  if (error.response.status === 401) {
    userStore.clearUserInfo()
    addressStore.clearAddressInfo()
    //当前前端路径
    const currentPath = router.currentRoute.value.path;

    if (currentPath.startsWith('/Seller/')) {
      ElMessage.warning('卖家登录已过期，请先登录');
      router.push('/seller/login'); // 卖家相关页面跳卖家登录
    } else if (currentPath.startsWith('/Admin/')) {
      router.push('/admin/login'); // 管理员相关页面跳管理员登录
    } else {
      if (userStore.userInfo) {
        ElMessage({
          type: 'warning',
          message: '登录已过期，请先登录'
        })
        //如果是token过期
        cartStore.clearCart()
      } else {
        ElMessage({
          type: 'warning',
          message: '请先登录'
        })
      }
      router.push('/login'); // 默认跳通用登录页
    }
  } else {
    //统一错误提示
    ElMessage({
      type: 'warning',
      message: '服务错误'
    })
  }
  return Promise.reject(error);
});


export default httpInstance